#include "log.h"
#include <stdio.h>
#include <stddef.h>
#include <time.h>
#include <string.h>
#include <android/log.h>

#define NEW_LINE "\n"

static FILE* log_file = NULL;
static int log_initialized = 0;

static void prefix(FILE* file, int prio, const char *tag);
static void suffix(FILE* file);

void log_initialize(const char * path) {
	if (log_initialized == 0) {
		log_file = fopen(path, "a+");
		log_initialized = 1;
	}
}

void log_write(int prio, const char *tag, const char *text) {
	__android_log_write(prio, tag, text);

	if (log_file != NULL) {
		prefix(log_file, prio, tag);
		fwrite(text, sizeof(char), sizeof(text), log_file);
		suffix(log_file);
		fflush(log_file);
	}
}

void log_print(int prio, const char *tag, const char *fmt, ...) {
	va_list ap;
	va_start(ap, fmt);

	__android_log_vprint(prio, tag, fmt, ap);

	if (log_file != NULL) {
		prefix(log_file, prio, tag);
		vfprintf(log_file, fmt, ap);
		suffix(log_file);
		fflush(log_file);
	}

	va_end(ap);
}

void log_vprint(int prio, const char *tag, const char *fmt, va_list ap) {
	__android_log_vprint(prio, tag, fmt, ap);

	if (log_file != NULL) {
		prefix(log_file, prio, tag);
		vfprintf(log_file, fmt, ap);
		suffix(log_file);
		fflush(log_file);
	}
}

void prefix(FILE* file, int prio, const char *tag) {
	char buff[256];

	time_t t;
	time(&t);
	struct tm* tm = localtime(&t);
	strftime(buff, 256, "%Y-%m-%d %H:%M:%S.000", tm);

	strcat(buff, " ");
	strcat(buff, tag);
	strcat(buff, " ");

	fwrite(buff, sizeof(char), strlen(buff), file);
}

void suffix(FILE* file) {
	fwrite("\r\n", sizeof(char), 2, file);
}
